<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;

class Cate extends Model
{
    use Notifiable;
    use SoftDeletes;
    /**
     * 需要转换成日期的属性
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    protected $table = 'cates';

    // 分类
    public static function getList($request)
    {
        $query = self::select('*');
        if (isset($request->parent_id)) {
            $query->where('parent_id', $request->parent_id);
        }
        if (isset($request->status) && $request->status) {
            $query->where('status', $request->status);
        }
        if (isset($request->name) && $request->name) {
            $query->where('name', 'like', '%' . $request->name . '%');
        }
        if (isset($request->sort) && $request->sort) {
            $query->orderBy($request->sort, $request->order);
        } else {
            $query->orderBy('id', 'desc');
        }
        $res = $query->paginate($request->size);
        return $res ? $res->toArray() : [];
    }

    // 分类详情
    public static function getInfo($id)
    {
        $res = self::select('*')->where('id', $id)->first();
        return $res ? $res->toArray() : [];
    }

    // 删除分类
    public static function del($id)
    {
        $res = static::where('id', $id)->delete();
        return $res;
    }

    // 定义递归关系
    public function children()
    {
        return $this->hasMany(Cate::class, 'parent_id')->with('children');
    }

    // 获取所有分类，以树形结构返回
    public static function getAllAsTree($request)
    {
        $query = self::select('*');
        $query->where('parent_id', 0);
        if (isset($request->status) && $request->status) {
            $query->where('status', $request->status);
        }
        if (isset($request->sort) && $request->sort) {
            $query->orderBy($request->sort, $request->order);
        } else {
            $query->orderBy('id', 'desc');
        }
        $categories = $query->get(); // 获取顶级分类

        foreach ($categories as $category) {
            if (isset($request->status) && $request->status) {
                $category->setRelation('children', $category->children()->where('status', $request->status)->orderBy('sort', 'asc')->get());  // 加载子分类
            } else {
                $category->setRelation('children', $category->children()->orderBy('sort', 'asc')->get());  // 加载子分类
            }
        }

        return $categories;
    }
}
